import Category from '../database/schema/Category.js'

const findCategory = (label) => {
  return new Promise((resolve, reject) => {
    Category.findOne({ label }, (err, doc) => {
        if(err){
            reject(err);
        }
        resolve(doc);
    });
  });
};

const findCategoryById = (_id) => {
  return new Promise((resolve, reject) => {
    Category.findOne({_id}, (err, doc) => {
      if(err){
        reject(err)
      }
      resolve(doc)
    })
  })
}
const delCategory = function(_id){
  return new Promise(( resolve, reject) => {
    Category.findOneAndRemove({ _id: _id }, err => {
          if(err){
              reject(err);
          }
          resolve();
      });
  });
};
const findAllCategory = () => {
  return new Promise((resolve, reject) => {
    Category.find({}, (err, doc) => {
      if(err){
          reject(err);
      }
      resolve(doc);
    });
  });
};

const Insert = async ( ctx ) => {
  let data = ctx.request.body
  if(!data.label){
    return successRes(ctx, -10, '', '参数不能为空')
  }
  let doc = await findCategory(data.label)
  if(doc){
    ctx.status = 200;
    return successRes(ctx, -10, '', '数据已存在')
  }
  let seat = new Category({
    label: data.label,
    desc: data.desc
  });
  await new Promise((resolve, reject) => {
    seat.save((err) => {
          if(err){
              reject(err);
          }
          resolve();
      });
  });
  return successRes(ctx, 0, '', '保存成功')
};

const Fetch = async( ctx ) => {
  let data = ctx.request.query
  if(data._id){
    let doc = await findCategoryById(data._id)
    ctx.status = 200;
    ctx.body = {
        code: 0,
        data: doc
    };
  }else{
    let doc = await findAllCategory()
    return successRes(ctx, 0, doc, '查询成功')
  }
};

const Update = async ( ctx ) => {
  let data = ctx.request.body
  await new Promise((resolve, reject) => {
    Category.findByIdAndUpdate({"_id" : data._id}, {$set: { label: data.label }},  function(err,docs){
      if(err){
        reject(err);
      }
      resolve()
    })
  })
  return successRes(ctx, 0, '', '更新成功')
}

const Delete = async (ctx) => {
  let _id = ctx.request.body._id;
  await delCategory(_id);
  return successRes(ctx, 0, '', '删除成功')
}

function successRes (ctx, code, data, msg) {
  ctx.status = 200;
  ctx.body = {
    code: code,
    data: data,
    msg: msg,
    userMsg: msg
  };
}


module.exports = {
  Insert,
  Fetch,
  Update,
  Delete
};